// pages/plaza/plaza.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    allMatchList: [
      {
        id: 1,
        username: '学霸小王',
        avatar: '../../assets/icons/avatar-placeholder.png',
        examName: 'CET-6',
        examDays: 25,
        startTime: '09:00',
        endTime: '11:00',
        timeDesc: '2小时',
        startDateTime: new Date(Date.now() + 30 * 60 * 1000),
        isMatched: false,
        status: 'waiting',
        message: '一起冲刺六级，互相监督！'
      },
      {
        id: 2,
        username: '努力小李',
        avatar: '../../assets/icons/avatar-placeholder.png',
        examName: '考研英语',
        examDays: 45,
        startTime: '14:00',
        endTime: '17:00',
        timeDesc: '3小时',
        startDateTime: new Date(Date.now() + 2 * 60 * 60 * 1000),
        isMatched: false,
        status: 'waiting',
        message: '考研路上不孤单，寻找学习伙伴'
      },
      {
        id: 3,
        username: '刷题达人',
        avatar: '../../assets/icons/avatar-placeholder.png',
        examName: 'CET-4',
        examDays: 15,
        startTime: '19:00',
        endTime: '21:00',
        timeDesc: '2小时',
        startDateTime: new Date(Date.now() + 5 * 60 * 60 * 1000),
        isMatched: false,
        status: 'waiting',
        message: '晚上一起刷题，效率更高！'
      },
      {
        id: 4,
        username: '早起鸟儿',
        avatar: '../../assets/icons/avatar-placeholder.png',
        examName: '托福',
        examDays: 60,
        startTime: '06:00',
        endTime: '08:00',
        timeDesc: '2小时',
        startDateTime: new Date(Date.now() + 24 * 60 * 60 * 1000),
        isMatched: false,
        status: 'waiting',
        message: '早起学习，一日之计在于晨'
      },
      {
        id: 5,
        username: '夜猫子小张',
        avatar: '../../assets/icons/avatar-placeholder.png',
        examName: 'CET-6',
        examDays: 30,
        startTime: '22:00',
        endTime: '24:00',
        timeDesc: '2小时',
        startDateTime: new Date(Date.now() + 8 * 60 * 60 * 1000),
        isMatched: false,
        status: 'waiting',
        message: '深夜学习更专注，寻找同道中人'
      },
      {
        id: 6,
        username: '考试小能手',
        avatar: '../../assets/icons/avatar-placeholder.png',
        examName: '雅思',
        examDays: 40,
        startTime: '10:00',
        endTime: '12:00',
        timeDesc: '2小时',
        startDateTime: new Date(Date.now() + 3 * 60 * 60 * 1000),
        isMatched: false,
        status: 'waiting',
        message: '雅思冲7分，一起加油！'
      },
      {
        id: 7,
        username: '勤奋小蜜蜂',
        avatar: '../../assets/icons/avatar-placeholder.png',
        examName: 'CET-4',
        examDays: 20,
        startTime: '16:00',
        endTime: '18:00',
        timeDesc: '2小时',
        startDateTime: new Date(Date.now() + 4 * 60 * 60 * 1000),
        isMatched: false,
        status: 'waiting',
        message: '四级必过，互相鼓励！'
      },
      {
        id: 8,
        username: '学习达人',
        avatar: '../../assets/icons/avatar-placeholder.png',
        examName: '考研数学',
        examDays: 90,
        startTime: '08:00',
        endTime: '11:00',
        timeDesc: '3小时',
        startDateTime: new Date(Date.now() + 12 * 60 * 60 * 1000),
        isMatched: false,
        status: 'waiting',
        message: '数学刷题不停歇，寻找学习伙伴'
      },
      {
        id: 9,
        username: '英语爱好者',
        avatar: '../../assets/icons/avatar-placeholder.png',
        examName: 'CET-6',
        examDays: 35,
        startTime: '15:00',
        endTime: '17:00',
        timeDesc: '2小时',
        startDateTime: new Date(Date.now() + 6 * 60 * 60 * 1000),
        isMatched: false,
        status: 'waiting',
        message: '英语学习路上，一起进步！'
      },
      {
        id: 10,
        username: '专注小王子',
        avatar: '../../assets/icons/avatar-placeholder.png',
        examName: '专四',
        examDays: 50,
        startTime: '13:00',
        endTime: '15:00',
        timeDesc: '2小时',
        startDateTime: new Date(Date.now() + 7 * 60 * 60 * 1000),
        isMatched: false,
        status: 'waiting',
        message: '专四冲刺，需要学习搭档！'
      },
      {
        id: 11,
        username: '已组队用户1',
        avatar: '../../assets/icons/avatar-placeholder.png',
        examName: 'CET-6',
        examDays: 25,
        startTime: '09:00',
        endTime: '11:00',
        timeDesc: '2小时',
        startDateTime: new Date(Date.now() + 30 * 60 * 1000),
        isMatched: true,
        status: 'matched',
        message: '已找到学习伙伴'
      },
      {
        id: 12,
        username: '已组队用户2',
        avatar: '../../assets/icons/avatar-placeholder.png',
        examName: '考研英语',
        examDays: 45,
        startTime: '14:00',
        endTime: '17:00',
        timeDesc: '3小时',
        startDateTime: new Date(Date.now() + 2 * 60 * 60 * 1000),
        isMatched: true,
        status: 'matched',
        message: '已找到学习伙伴'
      }
    ],
    matchList: [], // 只显示未组队的用户
    countdownTimer: null,
    hasMatched: false,
    matchedId: null,
    // 分页相关
    currentPage: 1,
    pageSize: 10,
    hasMore: true,
    loading: false
  },

  // 检查登录状态
  checkLoginStatus() {
    const token = wx.getStorageSync('local_token');
    if (!token) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      wx.navigateTo({
        url: '/subpkg/pages/login/login'
      });
      return false;
    }
    return true;
  },

  // 过滤未组队的用户
  filterUnmatchedUsers() {
    const unmatchedList = this.data.allMatchList.filter(item => !item.isMatched);
    this.setData({
      matchList: unmatchedList
    });
  },
  
  // 加载匹配列表 - 模拟版本
  async loadMatchList(isRefresh = false) {
    if (this.data.loading || (!this.data.hasMore && !isRefresh)) {
      return;
    }

    this.setData({ loading: true });

    const token = wx.getStorageSync('local_token');
    if (!token) {
      this.setData({ loading: false });
      return;
    }
    
    try {
      // 模拟延迟
      await new Promise(resolve => setTimeout(resolve, 500));
      
      // 模拟匹配数据
      const mockMatchData = [
        {
          id: 1,
          username: '学霸小明',
          avatar: '../../assets/icons/avatar-placeholder.png',
          examName: 'CET-6',
          examDays: 30,
          startTime: '09:00',
          endTime: '11:00',
          timeDesc: '2小时',
          startDateTime: new Date(),
          isMatched: false,
          status: 'pending',
          message: '一起学习吧！'
        },
        {
          id: 2,
          username: '努力的小红',
          avatar: '../../assets/icons/avatar-placeholder.png',
          examName: '考研',
          examDays: 120,
          startTime: '14:00',
          endTime: '16:00',
          timeDesc: '2小时',
          startDateTime: new Date(),
          isMatched: false,
          status: 'pending',
          message: '一起冲刺！'
        },
        {
          id: 3,
          username: '进步的小刚',
          avatar: '../../assets/icons/avatar-placeholder.png',
          examName: 'CET-4',
          examDays: 45,
          startTime: '19:30',
          endTime: '21:30',
          timeDesc: '2小时',
          startDateTime: new Date(),
          isMatched: true,
          status: 'accepted',
          message: '已匹配，准备学习！'
        }
      ];
      
      // 模拟分页
      const page = isRefresh ? 1 : this.data.currentPage;
      const startIndex = (page - 1) * this.data.pageSize;
      const endIndex = startIndex + this.data.pageSize;
      const currentPageData = mockMatchData.slice(startIndex, endIndex);
      
      // 确保startDateTime是Date对象
      const processedData = currentPageData.map(item => ({
        ...item,
        startDateTime: item.startDateTime instanceof Date ? item.startDateTime : new Date(item.startDateTime)
      }));
      
      // 更新数据
      const newMatchList = isRefresh ? processedData : [...this.data.matchList, ...processedData];
      
      this.setData({
        matchList: newMatchList,
        currentPage: page + 1,
        hasMore: endIndex < mockMatchData.length,
        loading: false
      });
    } catch (error) {
      console.error('加载匹配列表失败:', error);
      this.setData({ 
        loading: false,
        matchList: []
      });
      wx.showToast({
        title: '加载失败，请重试',
        icon: 'none',
        duration: 2000
      });
    }
  },
  


  // 格式化时间
  formatTime(dateTimeString) {
    const date = new Date(dateTimeString);
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    return `${hours}:${minutes}`;
  },
  
  // 计算时长
  calculateDuration(startTime, endTime) {
    const start = new Date(startTime);
    const end = new Date(endTime);
    const diffMs = end - start;
    const diffHours = diffMs / (1000 * 60 * 60);
    
    if (diffHours >= 1) {
      const hours = Math.floor(diffHours);
      const minutes = Math.round((diffHours - hours) * 60);
      return minutes > 0 ? `${hours}小时${minutes}分钟` : `${hours}小时`;
    } else {
      const minutes = Math.round(diffHours * 60);
      return `${minutes}分钟`;
    }
  },

  /**
   * 组队学习按钮点击事件
   */
  joinTeam: async function(e) {
    const matchId = e.currentTarget.dataset.id;
    const token = wx.getStorageSync('local_token');
    
    if (!token) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }
    
    const matchIndex = this.data.matchList.findIndex(item => item.id === matchId);
    if (matchIndex === -1) return;
    
    const currentMatch = this.data.matchList[matchIndex];
    
    try {
      // 模拟延迟
      await new Promise(resolve => setTimeout(resolve, 500));
      
      if (currentMatch.isMatched) {
        // 模拟取消匹配
        wx.showToast({
          title: '已取消匹配',
          icon: 'success',
          duration: 1500
        });
        
        // 更新allMatchList中对应用户的状态
        const allMatchList = [...this.data.allMatchList];
        const allMatchIndex = allMatchList.findIndex(item => item.id === matchId);
        if (allMatchIndex !== -1) {
          allMatchList[allMatchIndex].isMatched = false;
          allMatchList[allMatchIndex].status = 'waiting';
        }
        
        this.setData({
          allMatchList: allMatchList
        });
        
        // 重新过滤未组队用户列表
        this.filterUnmatchedUsers();
        
        // 清除匹配信息
        wx.removeStorageSync('currentMatch');
        wx.removeStorageSync('hasMatched');
      } else {
        // 模拟接受匹配
        wx.showToast({
          title: '匹配成功！',
          icon: 'success',
          duration: 1500
        });
        
        // 模拟匹配数据
        const mockMatchData = {
          study_session_id: `mock_session_${matchId}_${Date.now()}`,
          match_id: matchId,
          start_time: currentMatch.startTime,
          end_time: currentMatch.endTime,
          partner: currentMatch.username,
          partner_avatar: currentMatch.avatar,
          exam_name: currentMatch.examName,
          exam_days: currentMatch.examDays,
          message: currentMatch.message
        };
        
        // 保存匹配信息到本地存储
        wx.setStorageSync('currentMatch', mockMatchData);
        wx.setStorageSync('hasMatched', true);
        
        // 更新allMatchList中对应用户的状态
        const allMatchList = [...this.data.allMatchList];
        const allMatchIndex = allMatchList.findIndex(item => item.id === matchId);
        if (allMatchIndex !== -1) {
          allMatchList[allMatchIndex].isMatched = true;
          allMatchList[allMatchIndex].status = 'matched';
        }
        
        this.setData({
          allMatchList: allMatchList
        });
        
        // 重新过滤未组队用户列表
        this.filterUnmatchedUsers();
        
        // 跳转到督搭页面（首页）显示匹配成功状态
        setTimeout(() => {
          wx.switchTab({
            url: '/pages/index/index'
          });
        }, 1000);
      }
    } catch (error) {
      console.error('匹配操作失败:', error);
      wx.showToast({
        title: '操作失败，请重试',
        icon: 'none'
      });
    }
  },

  /**
   * 初始化开始时间
   */
  initStartTimes() {
    // 这个函数已经合并到onLoad中，保留以防其他地方调用
    const now = new Date();
    const matchList = this.data.matchList.map(item => {
      // 设置开始时间为今天的09:30
      const startDateTime = new Date();
      startDateTime.setHours(9, 30, 0, 0);
      
      // 如果当前时间已经过了今天的09:30，则设置为明天的09:30
      if (startDateTime.getTime() <= now.getTime()) {
        startDateTime.setDate(startDateTime.getDate() + 1);
      }
      
      return {
        ...item,
        startDateTime: startDateTime
      };
    });
    
    this.setData({
      matchList: matchList
    });
  },

  /**
   * 更新倒计时
   */
  updateCountdown() {
    const now = new Date();
    const matchList = this.data.matchList.map(item => {
      if (item.startDateTime) {
        // 确保startDateTime是Date对象
        const startDateTime = item.startDateTime instanceof Date ? item.startDateTime : new Date(item.startDateTime);
        const timeDiff = startDateTime.getTime() - now.getTime();
        
        if (timeDiff > 0) {
          const hours = Math.floor(timeDiff / (1000 * 60 * 60));
          const minutes = Math.floor((timeDiff % (1000 * 60 * 60)) / (1000 * 60));
          const seconds = Math.floor((timeDiff % (1000 * 60)) / 1000);
          
          if (hours > 0) {
            return {
              ...item,
              timeDesc: `${hours}小时${minutes}分后开始`
            };
          } else if (minutes > 0) {
            return {
              ...item,
              timeDesc: `${minutes}分${seconds}秒后开始`
            };
          } else {
            return {
              ...item,
              timeDesc: `${seconds}秒后开始`
            };
          }
        } else {
          return {
            ...item,
            timeDesc: '已开始'
          };
        }
      }
      return item;
    });
    
    this.setData({
      matchList: matchList
    });
  },

  /**
   * 开始倒计时
   */
  startCountdown() {
    // 延迟100ms后开始倒计时，避免与页面初始化冲突
    setTimeout(() => {
      this.updateCountdown();
      const timer = setInterval(() => {
        this.updateCountdown();
      }, 1000); // 每秒更新一次
      
      this.setData({
        countdownTimer: timer
      });
    }, 100);
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log('匹配广场页面加载');
    
    // 检查登录状态
    this.checkLoginStatus();
    
    // 过滤显示未组队的用户
    this.filterUnmatchedUsers();
    
    // 定时刷新匹配列表
    this.startAutoRefresh();
    
    // 启动倒计时
    this.startCountdown();
  },

  /**
   * 自定义导航栏返回按钮点击事件
   */
  onNavigationBarBackTap() {
    // 根据匹配状态返回督搭页
    if (this.data.hasMatched) {
      wx.navigateBack({
        delta: 1
      });
    } else {
      wx.navigateBack({
        delta: 1
      });
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    // 页面渲染完成后，确保数据显示正确
    console.log('匹配广场页面渲染完成');
  },

  // 开始自动刷新
  startAutoRefresh() {
    // 每30秒刷新一次匹配列表
    this.refreshTimer = setInterval(() => {
      this.loadMatchList(true);
    }, 30000);
  },
  
  // 停止自动刷新
  stopAutoRefresh() {
    if (this.refreshTimer) {
      clearInterval(this.refreshTimer);
      this.refreshTimer = null;
    }
  },
  
  // 手动刷新
  onRefresh() {
    // 下拉刷新时重新加载数据
    this.loadMatchList(true);
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    console.log('匹配广场页面显示');
    
    // 刷新匹配列表
    this.loadMatchList();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    // 页面隐藏时停止自动刷新
    this.stopAutoRefresh();
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    // 清除倒计时定时器
    if (this.data.countdownTimer) {
      clearInterval(this.data.countdownTimer);
    }
    // 页面卸载时停止自动刷新
    this.stopAutoRefresh();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    // 滚动到底部时加载更多数据
    console.log('滚动到底部，加载更多数据');
    this.loadMatchList(false);
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})


